package com.demo.test.other;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

public class ApiClientGet {
    private static final String APP_ID = "2cda0a9ffe754f06";
    private static final String APP_SECRET = "54f098c4029f9b9ed4afa1b1ec34c7e7";
    private static final String BASE_URL = "http://localhost:8080/openapi";

    public static void main(String[] args) throws Exception {
        // 1. 准备请求参数
        String path = "/api/v1/getInfo";
        String method = "GET";
        String nonce = UUID.randomUUID().toString();
        long timestamp = System.currentTimeMillis();

        // GET 请求参数（需按 Key 排序）
        Map<String, String> params = new TreeMap<>();
        params.put("param1", "测试");
        params.put("param2", "10");
        String queryString = buildQueryString(params); // 生成排序后的查询字符串

        // 2. 生成签名（参数数据为查询字符串）
        String signature = HmacSigner.generateSignature(
                APP_SECRET, method, path,
                String.valueOf(timestamp), nonce, queryString
        );

        // 3. 发送请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + path + "?" + queryString)
                .get()
                .header("X-App-Id", APP_ID)
                .header("X-Nonce", nonce)
                .header("X-Timestamp", String.valueOf(timestamp))
                .header("X-Signature", signature)
                .build();

        System.out.println("生成的签名为：" + signature);

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("Response: " + response.body().string());
            } else {
                System.out.println("Error: " + response.code() + " - " + response.body().string());
            }
        }
    }

    // 构建排序后的查询字符串
    private static String buildQueryString(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString();
    }
}
